from pathlib import Path

from BeautifulReport import BeautifulReport
import yamail
import logging

from Config.Config import Config


class Tools():
    def __init__(self):
        self.cfg = Config()
        self.logger = self.get_logger('Tools')

    @staticmethod
    def resolve_path(relative_path):
        """
        动态解析项目内任意层级的文件路径
        :param relative_path: 相对于项目根目录的路径，如 "Data/accountInfo.yaml"
        :return: 绝对路径字符串
        """
        # 获取项目根目录（假设Tools.py在LongGuoUI/Tools/下）
        base_dir = Path(__file__).parent.parent
        # 拼接并标准化路径
        return str((base_dir / relative_path).resolve())

    # 报告
    def report(self, suite,):
        '''
        封装报告方法
        :param suite:
        :return:
        '''
        report = BeautifulReport(suite).report(description='共执行三个模块的测试用例', filename='result.html',
                                               report_dir=Tools.resolve_path("Report"))
        return report

    # 邮件
    def email(self, subject, content,
              attachments=None,
              sender=Config().get_sender(),
              password=Config().get_authorization_code(),
              recipient=Config().get_recipient(),
              host=Config().get_host(),
              port=Config().get_port()):
        """
        发送带附件的邮件
        :param subject: 邮件主题（必需）
        :param content: 邮件正文（必需）
        :param sender: 发件人，默认从Config读取
        :param password: 授权码，默认从Config读取
        :param recipient: 收件人，默认从Config读取
        :return: bool 是否发送成功
        """
        try:
            # 准备附件

            for file in attachments:
                path = Tools.resolve_path(file)
                if not Path(path).exists():
                    self.logger.info('邮件附件不存在')

            # 发送邮件
            with yamail.SMTP(user=sender, password=password,
                             host=host, port=port) as email:
                email.send(
                    to=recipient,
                    subject=subject,
                    contents=content,
                    attachments=attachments
                )
            return True
        except Exception as e:
            self.logger.error(f"邮件发送失败: {str(e)}")
            return False


    # 日志 (可以同时输出到控制台和日志)
    def get_logger(self, name='UIAutomation'):
        """获取配置好的logger对象（带防重复创建检查）"""
        logger = logging.getLogger(name)
        if not logger.handlers:  # 避免重复添加handler
            logger.setLevel(logging.DEBUG)  # ← 这里的level控制logger本身

        # 控制台handler
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)  # ← 可单独设置handler级别

        # 文件handler
        file_handler = logging.FileHandler(Tools.resolve_path("Log/Log.log"), encoding='utf-8')
        file_handler.setLevel(logging.DEBUG)  # ← 文件记录更详细级别

        # 添加格式和handler
        formatter = logging.Formatter('%(lineno)d - %(name)s - %(levelname)s - %(message)s - %(asctime)s')
        console_handler.setFormatter(formatter)
        file_handler.setFormatter(formatter)
        logger.addHandler(console_handler)
        logger.addHandler(file_handler)

        return logger  # ← 返回配置好的logger对象
